package com.jun.admin.core.service.impl;

import com.jun.admin.core.mapper.AdminOrganizationMapper;
import com.jun.admin.core.model.AdminOrganization;
import com.jun.admin.core.model.vo.OrgTreeVo;
import com.jun.admin.core.service.OrgService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author yuejun.li
 * @date 2024/10/15 16:08:38
 */
@Service
@AllArgsConstructor
@Slf4j
public class OrgServiceImpl implements OrgService {

    private AdminOrganizationMapper organizationMapper;

    @Override
    public List<OrgTreeVo> tree() {
        List<AdminOrganization> organizations = organizationMapper.selectAll();

        return organizations.stream()
                .filter(f -> Objects.equals(f.getPOrgId(),"0"))
                .map(root -> {
                    OrgTreeVo orgTreeVo = new OrgTreeVo();
                    orgTreeVo.setOrgId(root.getOrgId());
                    orgTreeVo.setOrgName(root.getOrgName());
                    orgTreeVo.setChildren(getChildren(organizations,root));
                    return orgTreeVo;
                }).collect(Collectors.toList());
    }


    private List<OrgTreeVo> getChildren(List<AdminOrganization> organizations, AdminOrganization item) {
        return organizations.stream()
                .filter(f -> Objects.equals(item.getOrgId(),f.getPOrgId()))
                .map(child -> {
                    OrgTreeVo orgTreeVo = new OrgTreeVo();
                    orgTreeVo.setOrgId(child.getOrgId());
                    orgTreeVo.setOrgName(child.getOrgName());
                    orgTreeVo.setChildren(getChildren(organizations,child));
                    return orgTreeVo;
                }).collect(Collectors.toList());
    }
}
